<template>
  <Mentionable
    :keys="keys"
    :items="items"
    offset="6"
    insert-space
    @open="onOpen"
  >
    <textarea v-model="text" />

    <template #no-result>
      <div class="dim">No result</div>
    </template>

    <!-- <template #item-@="{ item }">
      <div class="suggestion">
        {{ item.value }}
        <span class="dim"> ({{ item.label }}) </span>
      </div>
    </template> -->
  </Mentionable>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue';
import { Mentionable } from 'vue-mention';
import 'floating-vue/dist/style.css';

const props = defineProps({
  keys: {
    type: Array as () => string[],
    default: () => ['@', '#', '$']
  },
  options: {
    type: Array as () => any[],
    default: () => [
      { value: 'akryum', label: 'Guillaume', searchText: 'akryum' },
      { value: 'posva', label: 'Eduardo', searchText: 'posva' },
      { value: 'atinux', label: 'Sébastien', searchText: 'atinux' },
    ]
  }
});

const text = ref('');
const currentKey = ref<string | null>(null);

const items = computed(() => {
  if (!currentKey.value) return props.options;
  const isVariable = (opt: any) => typeof opt?.value === 'string' && /^\{.+\}$/.test(opt.value);
  if (currentKey.value === '$') {
    return props.options.filter(isVariable);
  }
  return props.options.filter(opt => !isVariable(opt));
});

function onOpen(key: string) {
  currentKey.value = key;
}
</script>

<style>
.mention-item {
  padding: 4px 8px;
  cursor: pointer;
}
.mention-selected {
  background: rgb(192, 250, 153);
}
</style>
